<?php

namespace app\admin\controller;

use app\admin\model\Orders as OrdersModel;
use app\common\controller\Backend;
use app\common\exception\BusinessException;
use app\common\service\OrderStatus;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Orders extends Backend
{

    /**
     * Orders模型对象
     * @var \app\admin\model\Orders
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Orders;
        $cancelReasonList = $this->model->getCancelReasonList();
        $rejectionReasonList = $this->model->getRejectionReasonList();
        $this->view->assign('cancelReasonList', $cancelReasonList);
        $this->view->assign('rejectionReasonList', $rejectionReasonList);
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
        $this->view->assign("deliveryStatusList", $this->model->getDeliveryStatusList());
        $this->view->assign("tablewareStatusList", $this->model->getTablewareStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            // 状态类型
            $type  = $this->request->request('type');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if (empty($type) || $type == 'all') {
                $list = $this->model
                    ->with(['user', 'book', 'details'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            } else {
                $list = $this->model
                    ->with(['user', 'book', 'details'])
                    ->where($where)
                    ->where('orders.status', $type)
                    ->order($sort, $order)
                    ->paginate($limit);
            }


            foreach ($list as $row) {
                $row->visible(['id', 'number', 'remark', 'order_time', 'tableware_number', 'status', 'estimated_delivery_time', 'phone', 'address']);
                $row->visible(['user']);
                $row->getRelation('user')->visible(['username']);
                $row->visible(['book']);
                $row->getRelation('book')->visible(['detail']);
                $row->visible(['details']);
                $row->getRelation('details');
            }

            $listItems =  [];
            foreach ($list->items() as $key => $item) {
                $details = '';
                if ($item['details']) {
                    foreach ($item['details'] as $key => $detail) {
                        $details .= $detail['name'] . '*' . $detail['number'] . ';';
                    }
                }
                $listItems[] = [
                    'id' => $item->id,
                    'number' => $item->number,
                    'remark' => $item->remark,
                    'order_time' => $item->order_time,
                    'tableware_number' => $item->tableware_number,
                    'status' => $item->status,
                    'estimated_delivery_time' => $item->estimated_delivery_time,
                    'phone' => $item->phone,
                    'address' => $item->address,
                    'user' => ['username' => $item->user->username],
                    'order_dish' => $details,
                ];
            }

            $result = array("total" => $list->total(), "rows" => $listItems);

            return json($result);
        }

        //   $id = $this->request->request('id');
        // if ($id) {
        //    $this->assignconfig('id',$id);
        // }
        return $this->view->fetch();
    }


    /**
     * 查看详情
     *
     */
    public function detail($ids)
    {
        $order =  OrdersModel::get($ids);
        if (!$order) {
            throw new BusinessException("没有找到订单");
        }

        $result = [
            'id' => $order->id,
            'number' => $order->number,
            'status' => $order->status,
            'statusText' => $order->status_text,
            'userName' => $order->user->username,
            'address' => $order->address,
            'remark' => $order->remark,
            'orderTime' => $order->order_time,
            'amount' => $order->amount,
            'phone' => $order->phone,
            'packAmount' => $order->pack_amount,
        ];
        $details = $order->details;
        $detailList = [];
        $total = 0;
        if ($details) {
            foreach ($details as $key => $detail) {
                $total += $detail->number;
                $detailList[] = [
                    'name' => $detail->name,
                    'number' => $detail->number,
                    'amount' => $detail->amount,
                ];
            }
        }
        $result['detailList'] = $detailList;
        $result['total'] = $total;

        $this->view->assign('result', $result);
        return $this->view->fetch();
    }

    /**
     * 查看详情
     *
     */
    public function cancel($ids)
    {
        $order =  OrdersModel::get($ids);
        if (!$order) {
            throw new BusinessException("没有找到订单");
        }

        $this->view->assign('orderId', $order->id);
        return $this->view->fetch();
    }
}
